<?php
include_once "baseChannel.php";

class pingan extends baseChannel
{
    public $appid;
    public $apikey;

    public function __construct($setting)
    {
        parent::__construct($setting);
        $this->appid = $setting['appid'];
        $this->apikey = $setting['apikey'];
    }
    /*通用签名方法*/
    public function getSign($params)
    {
        unset($params['sign']);
        foreach ($params as $k => $v) {
            if (empty($v)) {
                unset($params[$k]);
            }
        }
        ksort($params);
        $params['apikey'] = $this->apikey;
        $str = http_build_query($params);
        $str = urldecode($str);
        //        echo "签名字符串：".$str.PHP_EOL;
        $sign = md5($str);
        return strtoupper($sign);
    }
    // public function checkOrder($mobile, $code, $params = [])
    // {
    //     $url = $this->api_url;
    //     $post_data = [
    //         'act' => 'checkOrder',
    //         'uid' => $this->uid,
    //         'timestamp' => $this->timestamp,
    //         'mobile' => $mobile,
    //         // 'spec_code' => $code,
    //         // 'callback_url' => $this->callback_url,
    //         // 'user_order_sn' => $params['push_order_sn'],
    //     ];

    //     $sign = $this->getSign($post_data);
    //     $post_data['sign'] = $sign;

    //     $return_str = $this->httpRequest($url, 'POST', $post_data);
    //     $return_data = json_decode($return_str, 1);

    //     $ret = [
    //         'error' => -1,
    //         'msg' => '初始化',
    //         'channel_order' => $return_data['data']['order_sn'] ?? '',
    //         'post_data' => json_encode($post_data),
    //         'channel_data' => $return_str,
    //         'code' => 200,
    //         'channel_order_price' => $return_data['data']['price'] ?? null,
    //         'channel_balance' => null,
    //     ];
    //     if ($return_data['code'] == 200) {
    //         $ret['error'] = 0;
    //         $ret['msg'] = $return_data['msg'] ?? '下单成功';
    //     } else {
    //         //下单失败 1006 余额不足
    //         if (isset($return_data['code'])) {
    //             $ret['error'] = 1;
    //             $ret['code'] = 500;
    //             $ret['msg'] = $return_data['msg'] ?? '下单失败';
    //         }
    //     }

    //     return $ret;
    // }
    /*查询余额*/
    public function queryBalance($params = [])
    {
        $url = $this->api_url . "/v1/rechargeapi/phone/querybalance";

        $post_data = [
            'appid' => $this->appid,
            'timestamp' => $this->timestamp,
        ];

        $sign = md5($post_data['appid'] . $post_data['timestamp'] . $this->apikey);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);
        if ($return_data['code'] == 0) {
            return [
                'error' => 0,
                'msg' => '查询成功',
                'balance' => $return_data['data']['balance'] ?? 0, //余额
                'credit' =>  0, //授信
                'code' => 200
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['message'] ?? '查询失败',
            'code' => 500
        ];
    }
    // public function queryProduct($params = [])
    // {
    //     $url = $this->api_url;
    //     $post_data = [
    //         'act' => 'queryProduct',
    //         'uid' => $this->uid,
    //         'timestamp' => $this->timestamp,
    //     ];

    //     $sign = $this->getSign($post_data);
    //     $post_data['sign'] = $sign;

    //     $return_str = $this->httpRequest($url, 'POST', $post_data);
    //     $return_data = json_decode($return_str, 1);

    //     $product_map = [];
    //     if ($return_data['code'] == 200) {
    //         $product_list = $return_data['data'];
    //         foreach ($product_list as $product) {
    //             $items = $product['specs'];
    //             foreach ($items as $item) {
    //                 $channel_api_code = $item['spec_code'];
    //                 $channel_product_status = $item['status'];
    //                 $channel_product_price = $item['user_price'];

    //                 $product_map[$channel_api_code] = [
    //                     'channel_id' => $this->channel_id ?? 0,
    //                     'channel_api_code' => $channel_api_code,
    //                     'channel_product_status' => $channel_product_status,
    //                     'channel_product_price' => $channel_product_price,
    //                 ];
    //             }
    //         }

    //         return [
    //             'error' => 0,
    //             'msg' => '查询成功',
    //             'data' => $product_map ?? [], //余额
    //             'code' => 200
    //         ];
    //     }
    //     return [
    //         'error' => 1,
    //         'msg' => $return_data['msg'] ?? '查询失败',
    //         'code' => 500
    //     ];
    // }
    public function queryOrder($params)
    {
        $url = $this->api_url . "/v1/rechargeapi/phone/queryorder";
        $post_data = [
            'appid' => $this->appid,
            'timestamp' => $this->timestamp,
            'outersn' => $params['push_order_sn'],
        ];

        $sign = md5($post_data['appid'] . $post_data['outersn'] . $post_data['timestamp'] . $this->apikey);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        $return_data = json_decode($return_str, 1);

        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'voucher' => $return_data['data']['voucher'] ?? '', //凭证
            'post_data' => json_encode($post_data), //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        // 成功
        if ($return_data['code'] == 0 && $return_data['data']['status'] == 2) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '充值完成:' . $return_data['message'];
        }
        // 失败
        if ($return_data['code'] == 0 && $return_data['data']['status'] == 10) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '充值失败:' . $return_data['message'];
        }
        // // 不存在订单
        // if ($return_data['code'] == 1007) {
        //     $ret['error'] = 1;
        //     $ret['code'] = 404;
        //     $ret['order_status'] = -1;
        //     $ret['msg'] = '订单不存在:' . $return_data['msg'];
        // }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $url = $this->api_url . "/v1/rechargeapi/phone/neworder";
        $post_data = [
            'appid' => $this->appid,
            'callbackurl' => $this->callback_url,
            'outersn' => $params['push_order_sn'],
            'productcode' => $code,
            'phonenum' => $mobile,
            'face' => $params['face_value'],
            "price" => "",
            'timestamp' => $this->timestamp,
        ];

        $sign = md5($post_data['appid'] . $post_data['callbackurl'] . $post_data['face'] . $post_data['outersn'] . $post_data['phonenum'] . $post_data['price'] . $post_data['productcode'] . $post_data['timestamp'] . $this->apikey);
        $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data);
        // var_dump("return_str");
        // var_dump($return_str);
        $return_data = json_decode($return_str, 1);

        $ret = [
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['data']['sn'] ?? '',
            'post_data' => json_encode($post_data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' =>  null,
            'channel_balance' => null,
        ];
        // code = 5000 未定义的异常，记作成功（5分钟无结果可通过查单接口请求订单状态）
        if ($return_data['code'] == 0 || $return_data['code'] == 5000) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['message'] ?? '下单成功';
        } else {
            //下单失败 1006 余额不足
            if (isset($return_data['code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['message'] ?? '下单失败';
            }
        }

        return $ret;
    }

    public function callback($params)
    {
        $this->callback_params = $params;
        $this->channel_order_sn = trim($params['sn']);
        $this->push_order_sn = $params['outersn'];
        //返回参数
        $res = $this->initCallBackParam();
        //订单状态
        $order_status = $params['status'];
        $msg = $params['msg'] ?? '';
        //凭证
        $pz = $params['voucher'] ?? '';
        $res['voucher'] = $pz;

        $sign = md5($params['appid'] . $params['outersn'] . $params['sn'] . $params['status'] . $params['timestamp'] . $params['voucher'] . $this->apikey);

        if ($sign != $params['sign']) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            return $res;
        }

        if ($order_status == 2) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
            $res['resp_data'] = "{}";
        }

        if ($order_status == 10) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
            $res['resp_data'] = "{}";
        }
        return $res;
    }
}
